/**
 * Copyright(c): 2017 com.mjduan All rights reserved.
 * 项目名：learn-spring-web
 * 注意：未经作者允许，不得外传
 */
package com.mjduan.project.web;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author dmj1161859184@126.com 2018-07-27 15:49
 * @version 1.0
 * @since 1.0
 */
@Controller
public class CookieController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CookieController.class);
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @RequestMapping(value = "/cookie")
    @ResponseBody
    public CookieModel doProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        processCookieInRequest(req);
        System.out.println("接收到请求");
        Cookie cookie = new Cookie("myCookieName", "myCookieID1");
        resp.addCookie(cookie);
        if (atomicInteger.get() % 2 == 0) {
            cookie = new Cookie("myCookieName2", "myCookieID2");
        } else {
            cookie = new Cookie("myCookieName2", "myCookieID3");
        }
        atomicInteger.incrementAndGet();
        resp.addCookie(cookie);
        CookieModel model = new CookieModel();
        model.setDesc("This is a cookie test");
        return model;
    }

    private void processCookieInRequest(HttpServletRequest req) {
        System.out.println("获取Cookie开始");
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + " " + cookie.getValue() + " " + cookie.getVersion() + " " + cookie.getMaxAge());
        }
        System.out.println("获取Cookie结束");
    }

    private static class CookieModel {
        private String desc;

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }
}
